import { KeyOutlined, LogoutOutlined } from '@ant-design/icons';
import { Avatar, Menu } from 'antd';
import React, { useState } from 'react';
import HeaderDropdown from './HeaderDropdown';
import ChangePasswordForm from './ChangePasswordForm';
import styles from './index.less';
import avatar from '@/assets/avatar.png';
import { connect } from 'umi';

const AvatarDropdown = (props) => {
  const { dispatch, loginUser } = props;

  const [modalPwdVisible, setModalPwdVisible] = useState(false);

  const onMenuClick = (event) => {
    const { key } = event;

    if (key === 'logout') {
      dispatch({ type: 'login/logout' });
    } else if (key === 'changePwd') {
      setModalPwdVisible(true);
    }
  };

  const { name, username } = loginUser;

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="changePwd">
        <KeyOutlined />
        修改密码
      </Menu.Item>
      <Menu.Item key="logout">
        <LogoutOutlined />
        退出登录
      </Menu.Item>
    </Menu>
  );
  return (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={avatar} alt="avatar" />
          <span className="anticon">{name || username}</span>
        </span>
      </HeaderDropdown>
      <ChangePasswordForm visible={modalPwdVisible} onVisibleChange={setModalPwdVisible} />
    </>
  );
};

export default connect(({ login: { loginUser } }) => ({ loginUser }))(AvatarDropdown);
